<?php
class CommonUtil {
	
	
	/**
	 * 将字符串转换为INT值[常用于表单中某字段强制要求为数字，则需要先转换后，再对数字进行判断]
	 * @param unknown_type $str 要转换的字符串
	 * @example   "字符串" -> 0  / 空字符串 -> 0 / "123xsdt" -> 123  /  12.2223 -> 12  / "-12dds" -> -12
	 */
	static function parseInt($str){
		return (int)$str;
	}
	
	/**
	 * 新增客服JS代码
	 * @param $config 网站配置数据
	 */
	static function appendCustomerJSconfig($config){
		$js = "";
		//客服列表
		$customer_list = CustomerHelper::getList();
		$customer = CustomerHelper::uniqueList($customer_list);
		
		if(!empty($customer["qq_customer_list"]) || !empty($customer["ww_customer_list"] ) || !empty($customer["tel_customer_list"] )){
			$js .= '<link type="text/css" href="'.__APP__.'/static/css/kf/lrkf_blue.css" rel="stylesheet" />';
			$js .= '<script type="text/javascript" src="'.__APP__.'/static/js/lrkf.js"></script>';
			$js .= '<script language="javascript" type="text/javascript">';
			$js .= '$(function(){';
			$js .= '$("#lrkfwarp").lrkf({';
			$js .= 'defshow:true,';
			//QQ客服列表
			if(!empty($customer["qq_customer_list"])){
				$js .= 'qqs:[';
				foreach ($customer["qq_customer_list"] as $obj){
					$js .= '{"name":"'.$obj["customer_name"].'","qq":"'.$obj["customer_value"].'"}';
					if($obj["last"] != true){
						$js .= ',';
					}
				}
				$js .= '],';
			}
			//旺旺客服列表
			if(!empty($customer["ww_customer_list"])){
				$js .= 'ww:[';
				foreach ($customer["ww_customer_list"] as $obj){
					$js .= '{"name":"'.$obj["customer_name"].'","ww":"'.urlencode($obj["customer_value"]).'"}';
					if($obj["last"] != true){
						$js .= ',';
					}
				}
				$js .= '],';
			}
			//电话客服列表
			if(!empty($customer["tel_customer_list"])){
				$js .= 'ww:[';
				foreach ($customer["tel_customer_list"] as $obj){
					$js .= '{"name":"'.$obj["customer_name"].'","tel":"'.$obj["customer_value"].'"}';
					if($obj["last"] != true){
						$js .= ',';
					}
				}
				$js .= '],';
			}
			$js .= 'kftop:"140"';
			$js .= '});';
			$js .= '});';
			$js .= '</script>';
		}
		
		$config["footer_js_cont"] = htmlspecialchars_decode($config["footer_js_cont"]);
		$config["footer_js_cont"] = $js.$config["footer_js_cont"];
		return $config;
	}
	
	/**
	 * 生成随机字符串
	 * @param unknown_type $length 随机字符串长度
	 */
	static function generateStr($length = 8) {
		//密码字符集，可任意添加你需要的字符
		$chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-_ []{}<>~`+=,.;:/?';
		$password = '';
		for ( $i = 0; $i < $length; $i++ ){
			$password .= $chars[ mt_rand(0, strlen($chars) - 1) ];
		}
		return $password;
	}
	
	/**
	 * 获取文件列表
	 */
	public static function getFileList($dir) {
		$fileArray[]=NULL;
		if (false != ($handle = opendir ( $dir ))) {
			$i=0;
			while ( false !== ($file = readdir ( $handle )) ) {
				//去掉"“.”、“..”以及带“.xxx”后缀的文件
				if ($file != "." && $file != ".."&&strpos($file,".")) {
					$fileArray[$i]=$file;
					if($i==100){
						break;
					}
					$i++;
				}
			}
			//关闭句柄
			closedir ( $handle );
		}
		return $fileArray;
	}
	
	
	//转换字段的类型
	static function getColumnType($formType,$varchar_len,$desc){
		if($formType == FormType::$INPUT){
			$columnType = "VARCHAR({$varchar_len}) DEFAULT NULL";
		}elseif($formType == FormType::$TEXTAREA){
			$columnType = "text";
		}elseif($formType == FormType::$NUMBER){
			$columnType = "int(10) DEFAULT '0'";
		}elseif($formType == FormType::$SELECT){
			$columnType = "VARCHAR({$varchar_len}) DEFAULT NULL";
		}elseif($formType == FormType::$EDITOR){
			$columnType = "longtext";
		}elseif($formType == FormType::$IMAGE){
			$columnType = "varchar(255) DEFAULT NULL";
		}elseif($formType == FormType::$MULTI_IMAGE){
			$columnType = "text";
		}elseif($formType == FormType::$FILE){
			$columnType = "varchar(255) DEFAULT NULL";
		}elseif($formType == FormType::$MULTI_FILE){
			$columnType = "text";
		}
		$columnType .= " COMMENT '{$desc}'";
		return $columnType;
	}
	
	/**
	 * 获取导航栏类型
	 */
	public static function getCataType($catalog){
		if($catalog["catalog_type"] == CatalogType::$DYNAMIC_MODULE){
			$dynamicModule = DynamicModuleHelper::getObject("dynamic_module_id={$catalog["dynamic_module_id"]}");
			return $dynamicModule["module_name"];
		}
		return $catalog["catalog_type"];
	}
	
	/**
	 * 获取动态模块SQL语句
	 */
	public static function getDynamicModuleSaveOrUpdateSQL($post,$dynamicModule,$dynamicModuleFieldList,$type){
		$data = array();
		$tableName = C("DB_PREFIX").$dynamicModule["table_name"];
		//>>>>>>>>>>>color字段获取
		if($dynamicModule["is_system"] == 1){	
			//如果是系统表，则需对title提供颜色选择器
			$fieldArr["val"] = $post["color"];
			$fieldArr["type"] = "varchar";
			$data['color'] = $fieldArr;
		}
		//>>>>>>>>>>>timeline字段获取
		$fieldArr["val"] = strtotime($post["timeline"]);
		$fieldArr["type"] = "int";
		$data['timeline'] = $fieldArr;
		//>>>>>>>>>>>view_num字段获取
		$fieldArr["val"] = CommonUtil::parseInt($post["view_num"]);
		$fieldArr["type"] = "int";
		$data['view_num'] = $fieldArr;
		//>>>>>>>>>>>catalog_id字段获取
		$fieldArr["val"] = $post["catalog_id"];
		$fieldArr["type"] = "int";
		$data['catalog_id'] = $fieldArr;
		//>>>>>>>>>>>redirect_url字段获取
		$is_redirect = $post["is_redirect"];
		if(is_array($is_redirect)){
			$fieldArr["val"] = $post["redirect_url"];
			$fieldArr["type"] = "varchar";
			$data["redirect_url"] = $fieldArr;
			if(!ValidateUtil::isURL($fieldArr["val"])){
				echo CommonUtil::ajaxReturn(Status::$ERROR,"请输入正确的跳转网址！");
				exit();
			}
		}else{
			$fieldArr["val"] = "";
			$fieldArr["type"] = "varchar";
			$data["redirect_url"] = $fieldArr;
		}
		//>>>>>>>>>>>seo_keywords字段获取
		$seo_keywords = $post["seo_keywords"];
		if(!empty($seo_keywords)){
			$fieldArr["val"] = $seo_keywords;
			$fieldArr["type"] = "varchar";
			$data["seo_keywords"] = $fieldArr;
		}else{
			$fieldArr["val"] = CommonUtil::analyze($post["title"],3);
			$fieldArr["type"] = "varchar";
			$data["seo_keywords"] = $fieldArr;
		}
		//>>>>>>>>>>>seo_description字段获取
		$seo_description = $post["seo_description"];
		if(!empty($seo_description)){
			$fieldArr["val"] = $seo_description;
			$fieldArr["type"] = "varchar";
			$data["seo_description"] = $fieldArr;
		}else{
			$fieldArr["val"] = len($post["content"], 100);
			$fieldArr["type"] = "varchar";
			$data["seo_description"] = $fieldArr;
		}
		//>>>>>>>>>>>其他表单字段获取
		foreach ($dynamicModuleFieldList as $field){
			$fieldName = $field["field_name"];
			$fieldVal = $post[$fieldName];
			$fieldReg = stripslashes($field["validate_reg_cont"]);
			if($fieldName == "id" || $fieldName == "catalog_id" ||  $fieldName == "color"|| $fieldName == "timeline" || $fieldName == "view_num" || $fieldName == "is_redirect" || $fieldName == "redirect_url" || $fieldName == "seo_keywords" || $fieldName == "seo_description"){
				continue;
			}
			//正则验证....
			if(!empty($fieldReg)){
				if(!ValidateUtil::isPassReg($fieldVal, $fieldReg)){
					if(empty($field["error_tip"])){
						echo CommonUtil::ajaxReturn(Status::$ERROR, "请填写正确的{$field["field_desc"]}！");
						exit();
					}else{
						echo CommonUtil::ajaxReturn(Status::$ERROR, $field["error_tip"]);
						exit();
					}
				}
			}
			$fieldArr = array();
			if($field["form_type"] == FormType::$IMAGE || $field["form_type"] == FormType::$FILE){
				//单[图片/文件]上传
				$fileAddr = CommonUtil::getRemovedProductPath($post["{$fieldName}_text"]);	//获取到缩略图正式环境下的地址
				$fieldArr["val"] = $fileAddr;
			}elseif($field["form_type"] == FormType::$MULTI_IMAGE || $field["form_type"] == FormType::$MULTI_FILE){
				//多[图片/文件]上传
				$extra_file_text_arr = $post["{$fieldName}_text"] == NULL ? array() : $post["{$fieldName}_text"];	//+添加展示图片
				$extra_file_text_arr = CommonUtil::picListBlankFilter($extra_file_text_arr);	//对$extra_pic_text_arr进行过滤，如果数组中含有空白字符的，则过滤掉
				$i = 0;
				$file_list_addr = "";
				foreach ($extra_file_text_arr as $extra_file_text){	//+添加展示图片
					if($i != 0){
						$file_list_addr .= CommonType::$PIC_EXPLODE_CHAR;
					}
					$file_list_addr .= CommonUtil::getRemovedProductPath($extra_file_text);
					$i++;
				}
				$fieldArr["val"] = $file_list_addr;
			}elseif($field["form_type"] == FormType::$EDITOR){
				$fieldArr["val"] = htmlspecialchars(stripslashes($_POST[$fieldName]));
			}else{
				//其他表单
				$fieldArr["val"] = $fieldVal;
			}
			if($field["form_type"] == FormType::$NUMBER){
				$fieldArr["type"] = "int";
			}else{
				$fieldArr["type"] = "varchar";
			}
			$data[$fieldName] = $fieldArr;
		}
		$sql = "";
		if($type == 'GetUpdateSQL'){
			$sql = "UPDATE {$tableName} SET ";
			$i = 0;
			foreach ($data as $k=>$v){
				if($i != 0){
					$sql .= ",";
				}
				if($v["type"] == "varchar"){
					$sql .= "{$k}='{$v["val"]}'";
				}else{
					$sql .= "{$k}={$v["val"]}";
				}
				$i++;
			}
			$sql .= " WHERE id={$post["id"]}";
		}else{
			$columSQL = "";
			$columValSQL = "";
			$i = 0;
			foreach ($data as $k=>$v){
				if($i != 0){
					$columSQL .= ",";
					$columValSQL .= ",";
				}
				$columSQL .= $k;
				if($v["type"] == "varchar"){
					$columValSQL .= "'{$v["val"]}'";
				}else{
					$columValSQL .= $v["val"];
				}
				$i++;
			}
			$sql = "INSERT INTO {$tableName} ({$columSQL}) VALUES($columValSQL)";
		}
		
		return $sql;
		
	}
	
	/**
	 * 获取表单模块SQL语句
	 */
	public static function getReserveModuleSaveOrUpdateSQL($get,$post,$reserveModule,$reserveModuleFieldList,$type){
		$data = array();
		$tableName = C("DB_PREFIX").$reserveModule["table_name"];
		//>>>>>>>>>>>timeline字段获取
		$fieldArr["val"] = time();
		$fieldArr["type"] = "int";
		$data['timeline'] = $fieldArr;
		//>>>>>>>>>>>catalog_id字段获取
		$fieldArr["val"] = $get["catalog_id"];
		$fieldArr["type"] = "int";
		$data['catalog_id'] = $fieldArr;
		//>>>>>>>>>>>reserve_status字段获取
		$fieldArr["val"] = 0;
		$fieldArr["type"] = "int";
		$data['reserve_status'] = $fieldArr;
		//>>>>>>>>>>>其他表单字段获取
		foreach ($reserveModuleFieldList as $field){
			$fieldName = $field["field_name"];
			$fieldVal = $post[$fieldName];
			$fieldReg = stripslashes($field["validate_reg_cont"]);
			if($fieldName == "id" || $fieldName == "catalog_id" || $fieldName == "timeline" || $fieldName == "reserve_status"){
				continue;
			}
			//正则验证....
			if(!empty($fieldReg)){
				
				if(!ValidateUtil::isPassReg($fieldVal, $fieldReg)){
					if(empty($field["error_tip"])){
						echo CommonUtil::alertAndGoBack("请填写正确的{$field["field_desc"]}！");
						exit();
					}else{
						echo CommonUtil::alertAndGoBack($field["error_tip"]);
						exit();
					}
				}
			}
			$fieldArr = array();
			if($field["form_type"] == FormType::$IMAGE || $field["form_type"] == FormType::$FILE){
				//单[图片/文件]上传
				$fileAddr = CommonUtil::getRemovedProductPath($post["{$fieldName}_text"]);	//获取到缩略图正式环境下的地址
				$fieldArr["val"] = $fileAddr;
			}else{
				//其他表单
				$fieldArr["val"] = $fieldVal;
			}
			if($field["form_type"] == FormType::$NUMBER){
				$fieldArr["type"] = "int";
			}else{
				$fieldArr["type"] = "varchar";
			}
			$data[$fieldName] = $fieldArr;
		}
		$sql = "";
		if($type == 'GetUpdateSQL'){
			$sql = "UPDATE {$tableName} SET ";
			$i = 0;
			foreach ($data as $k=>$v){
				if($i != 0){
					$sql .= ",";
				}
				if($v["type"] == "varchar"){
					$sql .= "{$k}='{$v["val"]}'";
				}else{
					$sql .= "{$k}={$v["val"]}";
				}
				$i++;
			}
			$sql .= " WHERE id={$post["id"]}";
		}else{
			$columSQL = "";
			$columValSQL = "";
			$i = 0;
			foreach ($data as $k=>$v){
				if($i != 0){
					$columSQL .= ",";
					$columValSQL .= ",";
				}
				$columSQL .= $k;
				if($v["type"] == "varchar"){
					$columValSQL .= "'{$v["val"]}'";
				}else{
					$columValSQL .= $v["val"];
				}
				$i++;
			}
			$sql = "INSERT INTO {$tableName} ({$columSQL}) VALUES($columValSQL)";
		}
		
		return $sql;
		
	}
	
	/**
	 * 获得当前模版路径
	 */
	public static function getTemplatePath(){
		$config = WebConfigHelper::getObject();
		return "./themes/".$config["template_name"]."/";
	}
	
	//获取网站的相对文件夹。如果是在ROOT下，则为空，如果只是子文件夹，则显示子文件夹名称
	static function getDir(){
		$dir = dirname(_PHP_FILE_);
		if($dir == '/' || $dir == '\\'){
			$dir = "";
		}
		return $dir;
	}
	
	//中文分词
	public static function analyze($str,$keyword_num = 10){
		
		Vendor('Analyze.phpanalysis');
    	//初始化类
	    $pa = new PhpAnalysis('utf-8', 'utf-8', true);
	    //载入词典
	    $pa->LoadDict();
	    //执行分词
	    $pa->SetSource($str);
	    $pa->differMax = true;
	    $pa->unitWord = true;
	    $pa->differFreq = true;
	    
	    $pa->StartAnalysis(true);
	    return $pa->GetFinallyKeywords($keyword_num);
	    
	}
	
	/**
	 * 获取客户端IP地址
	 * @return string
	 */ 
	public static function get_client_ip() { 
	    if(getenv('HTTP_CLIENT_IP')){ 
	        $client_ip = getenv('HTTP_CLIENT_IP'); 
	    } elseif(getenv('HTTP_X_FORWARDED_FOR')) { 
	        $client_ip = getenv('HTTP_X_FORWARDED_FOR'); 
	    } elseif(getenv('REMOTE_ADDR')) {
	        $client_ip = getenv('REMOTE_ADDR'); 
	    } else {
	        $client_ip = $_SERVER['REMOTE_ADDR'];
	    } 
	    return $client_ip; 
	}
	
	/**
	* 获取服务器端IP地址
	 * @return string
	 */
	public static function get_server_ip() { 
	    if (isset($_SERVER)) { 
	        if($_SERVER['SERVER_ADDR']) {
	            $server_ip = $_SERVER['SERVER_ADDR']; 
	        } else { 
	            $server_ip = $_SERVER['LOCAL_ADDR']; 
	        } 
	    } else { 
	        $server_ip = getenv('SERVER_ADDR');
	    } 
	    return $server_ip; 
	}
	
	/**
	 * 获取图片列表【图片模块】
	 */
	static function getPicList($str){
		if(empty($str)){
			return null;
		}
		return explode(CommonType::$PIC_EXPLODE_CHAR, $str); 
	}
	
	/**
	 * 某个字符串是否包含在数组中...供[图片模块后台使用]
	 */
	static function isContainInArr($str4search,$arr){
		$isFind = false;
		foreach ($arr as $str){
			if($str4search == $str){
				return true;
			}
		}
		return $isFind;
	}
	

	/**
	 * 执行SQL脚本
	 */
	static function execSQL($sql_file){
		$arr = array();
		$lnk = mysql_connect(C('DB_HOST'),C('DB_USER'),C('DB_PWD'));
    	if (!mysql_select_db(C('DB_NAME'),$lnk)){
    		$arr["result"] = false;
    		$arr["msg"] = "数据库连接失败！错误详情为：".mysql_error()."/r/n";
    	}
    	if(empty($arr)){
	    	$errorMsg = DBUtil::populate_db( C('DB_NAME'),'', $sql_file);  
			if(empty($errorMsg)){
				$arr["result"] = true;
			}else {
				$arr["result"] = false;
	    		$arr["msg"] = $errorMsg;
			}
    	}
		mysql_close($lnk);
		return $arr;
	}
	
	/**
	 * 检查是否是目录方式的URL，如果不是，则自动跳转为目录URL。【自动以“/”结尾】
	 */
	static function checkCataUrlOrRedirect(){
		$request_uri = $_SERVER["REQUEST_URI"];
		if(CommonUtil::contain($request_uri, "?") || CommonUtil::contain($request_uri, ".")){
			return ;
		}
		$url_end_char = substr($request_uri, -1);
		if($url_end_char != "/"){	//该URL没有以"/"结尾，不是目录URL，需301
			$redirect_url = "http://".$_SERVER["HTTP_HOST"].$request_uri."/";
			header('HTTP/1.1 301 Moved Permanently');
			header("Location: $redirect_url");
			exit();
		}
	}
	
	/**
	 * 图片数组净化过滤【图片模块】，当数组里含有空的字符串时，过滤掉
	 */
	static function picListBlankFilter($arr){
		$arr4temp = array();
		$i = 0;
		foreach ($arr as $str){
			if(!empty($str)){
				$arr4temp[$i] = $str;
				$i++;
			}
		}
		return $arr4temp; 
	}
	
	public static function unzip($zipfile, $dest){
		$archive   = new ZipUtil();
		$array     = $archive->GetZipInnerFilesInfo($zipfile);
		$filecount = 0;
		$dircount  = 0;
		$failfiles = array();
		set_time_limit(0);  // 修改为不限制超时时间(默认为30秒)
		
		for($i=0; $i<count($array); $i++) {
		    if($array[$i][folder] == 0){
		        if($archive->unZip($zipfile, $dest, $i) > 0){
		            $filecount++;
		        }else{
		            $failfiles[] = $array[$i][filename];
		        }
		    }else{
		        $dircount++;
		    }
		}
		set_time_limit(30);
		$arr = array();
		$str = "文件夹:".$dircount."&nbsp;&nbsp;&nbsp;&nbsp;更新升级文件:".$filecount."&nbsp;&nbsp;&nbsp;&nbsp;失败:".count($failfiles)."<br />";
		if(count($failfiles) > 0){
		    $arr["result"] = false;
			foreach($failfiles as $file){
		        $str .= "&middot;".$file."<br />";
		    }
		}else{
			$arr["result"] = true;
		}
		$arr["msg"] = $str;
		return $arr;
	}
	
	/**
	 * 创建百度SITEMAP 节点
	 */
	static function create_baidu_site_node($url,$lastmod,$changefreq,$priority){
		$lastmod = date('Y-m-d', $lastmod);
		$str .= '<url>
    				<loc>'.$url.'</loc>
    				<lastmod>'.$lastmod.'</lastmod>
					<changefreq>'.$changefreq.'</changefreq>
					<priority>'.$priority.'</priority>
				</url>';
		return $str;
	}
	
	/**
	 * 创建谷歌SITEMAP 节点
	 */
	static function create_google_site_node($url,$lastmod,$changefreq,$priority){
		$s = date("Y-m-d",$lastmod);
		$s1 = date("H:i:s+00:00",$lastmod);
		$lastmodStr = $s.'T'.$s1;
		$str .= '<url>
    				<loc>'.$url.'</loc>
    				<lastmod>'.$lastmodStr.'</lastmod>
					<changefreq>'.$changefreq.'</changefreq>
					<priority>'.$priority.'</priority>
				</url>';
		return $str;
	}
	
	
	/**
	 * 判断用户是否登录
	 */
	static function isLogin(){
		$user = session ( "user" );
		if(empty($user)){
			return false;
		}
		return true;
	}
	
	/**
	 * 时间格式化
	 */
	static function formatDate($time){
		if(empty($time) || $time == 0){
			return "";
		}
		$rtime = date ( "m-d H:i", $time );
		$htime = date ( "H:i", $time );

		$time = time () - $time;

		if ($time < 60) {
			$str = '刚刚';
		} elseif ($time < 60 * 60) {
			$min = floor ( $time / 60 );
			$str = $min . '分钟前';
		} elseif ($time < 60 * 60 * 24) {
			$h = floor ( $time / (60 * 60) );
			$str = $h . '小时前 ' . $htime;
		} elseif ($time < 60 * 60 * 24 * 3) {
			$d = floor ( $time / (60 * 60 * 24) );
			if ($d == 1){
				$str = '昨天 ' . $rtime;
			}
			else{
				$str = '前天 ' . $rtime;
			}
		} else {
			$str = $rtime;
		}
		return $str;
	}
	
	/**
	 * 过滤输入内容中的html，转换成相应的字符
	 */
	public static function filterHtml($str){
		$str=trim($str);
		if (strlen($str) <=0){
			return $str;
		}
		$search= array ("'<script[^>]*?>.*?</script>'si",  // 去掉 javascript
				"'<[\/\!]*?[^<>]*?>'si",          // 去掉 HTML 标记
				"'([\r\n])[\s]+'",                // 去掉空白字符
				"'&(quot|#34);'i",                // 替换 HTML 实体
				"'&(amp|#38);'i",
				"'&(lt|#60);'i",
				"'&(gt|#62);'i",
				"'&(nbsp|#160);'i"
		);                    // 作为 PHP 代码运行
		
		$replace= array ("",
				"",
				"\\1",
				"\"",
				"&",
				"<",
				">",
				" "
		);
		
		return @preg_replace($search,$replace,$str);
	}
	
	/**
	 * 返回JSON结果
	 * $status 返回状态 0失败，1成功,2跳转，或者其他int扩展数 -1 代表未登录
	 * $msg 返回的扩展内容，如status为0的时候，则可以借用$msg来做错误提示。status为1成功时，则可以借用$msg来做一些成功的扩展操作
	 * $data 对应的扩展数据，如$result["name"]="wk"; $result["age"] = 12;   在JS中则可以调用result.data.age方式拿到数据
	 */
	static function ajaxReturn($status,$msg,$data = null){
		$result  =  array();
		$result['status']  =  $status;
		$result['msg'] =  $msg;
		if($data != null){
			$result['data'] = $data;
		}
		return json_encode($result);
	}
	
	/**
	 * 返回ALERT信息，并且返回上一个页面
	 */
	static function alertAndGoBack($msg){
		header("Content-Type: text/html; charset=utf-8");
		return '<script language="javascript">alert("'.$msg.'");history.back();</script>';
	}
	
	/**
	 * 获取文件后缀
	 * @param $filestr：文件整体路径
	 * 返回：文件后缀
	 */
	static public function getExtendName($filestr){
	    $gonten= explode('.',$filestr);
	    $gonten = array_reverse($gonten);
	    return strtolower($gonten[0]);
	}
	
	/**
	 *
	 * 日志记录调试
	 * @param $msg 要打印的消息
	 * @param $type 类型：w写入或a附加等
	 */
	public static function fwrite($msg,$path='./fwrite.txt',$type='w'){
		@$fp = fopen($path, $type);
		fwrite($fp, $msg.PHP_EOL);
		fclose($fp);
	}
	
	/**
	 * 判断当前服务器是否Linux
	 * @return boolean
	 */
	public static function isWebServerLinux() {
		return PATH_SEPARATOR==':';
	}
	
	//截取utf8字符串
	public static function utf8Substr($str, $from, $len){
	    return preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$from.'}'.
	                       '((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$len.'}).*#s',
	                       '$1',$str);
	}
	
	/**
	 * 生成UUID
	 * @param $prefix 在UUID上加入一个扩展前缀
	 */
	static function uuid($prefix = ''){
		$chars = md5(uniqid(mt_rand(), true));
		$uuid = substr($chars,0,8) . '-';
		$uuid .= substr($chars,8,4) . '-';
		$uuid .= substr($chars,12,4) . '-';
		$uuid .= substr($chars,16,4) . '-';
		$uuid .= substr($chars,20,12);
		return $prefix . $uuid;
	}
	
	
	//生成找回密码的唯一验证码
	static function generateFindbackCode($uid){
		return CommonUtil::uuid($uid."-");
	}
	
	/**
	 * 判断[str1字符串]是否包含[str2字符串]，不区别大小写
	 * @param $str1
	 * @param str2
	 * 返回 true 或 false
	 */
	static public function contain($str4source,$str4search){
		$index = strripos($str4source,$str4search);
		if($index === false){
			return false;
		}else{
			return true;
		}
	}
	
	/**
	 * 文件上传，普通FORM文件标签上传
	 * $uploadReturnArr = CommonUtil::upload("identification_card","身份证正面图", UploadFilePath::$FILE,array("gif","jpg","jpeg","png","bmp"));
	 * if($uploadReturnArr["result"] == false){
	 *		echo CommonUtil::alertAndGoBack($uploadReturnArr["msg"]);
	 *		return;
	 *	}
	 *	$data['identification_card_addr'] = $uploadReturnArr["msg"];
	 * @param $filename
	 * @param $storePath 文件的保存路径，如/uploads/file/
	 * @param $extArr 后缀名限制，如$extArr = array("gif","jpg","jpeg");
	 * @param $isAutoGenerate 是否自动生成名字
	 * @return multitype:boolean string
	 */
	static function upload($filename,$filename_desc,$storePath,$extArr=array(),$isAutoGenerate=true){
		$resultArr = array();
		if(empty($filename_desc)){
			$filename_desc = $filename;
		}
		if(empty($_FILES[$filename]["name"])){
			$resultArr["result"] = false;
			$resultArr["msg"] = "请上传".$filename_desc;
			return $resultArr;
		}
		
		$filetype = CommonUtil::getExtendName($_FILES[$filename]["name"]);
		
		$file4return = "";	//程序返回的文件路径
		$file = "";	//程序内部使用的文件路径
		
		if($isAutoGenerate == true || CommonUtil::containChineseStr($_FILES[$filename]["name"])){
			$today=date("YmdHis"); //获取时间并赋值给变量
			$file4return = $storePath.$today.".".$filetype; //文件的完整路径，供返回结果集用，同下区别在于，"./path/xx.gif" -> "/path/xx.gif"
			$storePath = ".".$storePath;
			$file = $storePath.$today.".".$filetype; //供程序使用的|文件的完整路径|
		}else{
			$filename2=str_replace(array(' '),'_',$_FILES[$filename]["name"]);	//将空格替换成“_”
			$file4return = $storePath.$filename2;
			$storePath = ".".$storePath;
			$file = $storePath.$filename2; //供程序使用的|文件的完整路径|
		}
		
		if(!file_exists($storePath)){
			//检查是否有该文件夹，如果没有就创建，并给予最高权限
			mkdir($storePath, 0700);
		}
		//检查上传文件是否在允许上传的类型
		if(!empty($extArr)){
			if(!in_array($filetype, $extArr)){
				$resultArr["result"] = false;
				$resultArr["msg"] = $filename_desc." 文件格式不正确！";
				return $resultArr;
			}
		}
	
		//$result = move_uploaded_file($_FILES[$filename]["tmp_name"],$file);	//不支持中文文件名
		$result = move_uploaded_file($_FILES[$filename]["tmp_name"],iconv("UTF-8","gb2312",$file));	//支持中文文件名
	
		//特别注意这里传递给move_uploaded_file的第一个参数为上传到服务器上的临时文件
		$resultArr["result"] = true;
		$resultArr["msg"] = $file4return;
		return $resultArr;
	}
	
	/**
	 * 是否含有中文字符串
	 */
	static function containChineseStr($str){
		if (preg_match("/[\x7f-\xff]/", $str)) { 
			return true;
		}else{ 
			return false; 
		} 
	}
	
	/**
	 * 删除文件
	 * @param $filepath 文件路径，如/uploads/file/xx.gif
	 */
	static function deleteFile($filepath){
		if(!CommonUtil::contain($filepath, "./")){
			$filepath = ".".$filepath;
		}
		//return unlink($filepath);	//不支持中文文件名删除
		return unlink(iconv("UTF-8","gb2312",$filepath));	//支持中文文件名删除
	}
	
	/**
	 * 将临时文件转移到正式环境中
	 */
	static function remove2ProductPath($tempfilepath){
		$productPath = CommonUtil::getRemovedProductPath($tempfilepath);
		copy(".".$tempfilepath,".".$productPath); //拷贝到正式目录
		CommonUtil::deleteFile($tempfilepath);	//删除临时文件
		return $productPath;
	}
	
	/**
	 * 获取转移到正式环境中的路径
	 */
	static function getRemovedProductPath($tempfilepath){
		$productPath = str_replace("/temp/", "/file/", $tempfilepath);
		return $productPath;
	}
	
	/**
	 * 
	 * 下载远程文件(开启CURL)，在后台判断用户的PHP环境是否开启CURL，如果没开启，则提示。
	 * CURL支持大文件下载，更稳定，不会超时
	 * @param $url 远程文件地址
	 * @param $dest 要存在的文件路径
	 * @example CommonUtil::download("http://www.baidu.com/logo.png","./uploads/xx.png");
	 */
	public static function download($url, $dest){
		$options = array(
			CURLOPT_FILE => is_resource($dest) ? $dest : fopen($dest, 'w'),
			CURLOPT_FOLLOWLOCATION => true,
			CURLOPT_URL => $url,
			CURLOPT_FAILONERROR => true, // HTTP code > 400 will throw curl error
		);
		
		$ch = curl_init();
		curl_setopt_array($ch, $options);
		$return = curl_exec($ch);
		
		if ($return === false){
			return curl_error($ch);
		}else{
			return true;
		}
	}
	
	/**
	 * 获取分页数据
	 * @param $sql
	 * @param $currentPage	//当前页数
	 * @param $numPerPage	//每页显示的条数
	 * @param $url 空则为缺省模式，自带?page=22参数，不为空，则为自定义模式
	 * @param $extendDisctionSQL   如果是DISTION特殊SQL语句时，则需要进行特殊的COUNT， 该参数未可变参数，如$extendDisctionSQL = "DISTINCT xtable.id";
	 * @author wangkun <wangking717@qq.com>
	 * @return $pagination数组array("htmlurl"=>$htmlurl, "resultList"=>$resultList);
	 * @example $url = __APP__."/todo/".CommonType::$PAGE_NUM_TAG."/";	//自定义URL分页路径模式： __APP__/todo/{:page}/
	 * 			$pagination = CommonUtil::getPage("select * from app_albums",$page,10,$url);	//自定义的分页调用
	 * 			$pagination = CommonUtil::getPage("select * from app_albums",$page,10);	//缺省默认的分页调用
	 * 			$this->assign("pagination",$pagination);
	 */
	public static function getPage($sql,$currentPage=1,$numPerPage=10,$extendDisctionSQL=NULL,$url=NULL,$isPureURL=TRUE){
		$model = M ();
	
		$isUrlDefault = 0;	//是否URL缺省模式标识
		if($url == null){	//使用URL缺省模式，则为page参数模式
			$url = $_SERVER["REQUEST_URI"];
			if(CommonUtil::contain($url,"page=")){	//传过来的URL值是否包含page参数
				$url = preg_replace("/page=\d*/","page=".CommonType::$PAGE_NUM_TAG,$url);
			}else{
				if(CommonUtil::contain($url,"?")){	//URL是否包含"？"问号
					$url .= "&";
				}else{
					$url .= "?";
				}
				$url .= "page=".CommonType::$PAGE_NUM_TAG;
			}
			$isUrlDefault = 1;
		}else{
			$url = __APP__.$url; 
		}
	
		//第一步：获取[总记录数]、[总页数]
		$sqlBak = strtolower($sql);	//将$sql进行lower case，以便组成SQL的正确性
		$sqlCount = "";
		if($extendDisctionSQL != null){
			$sqlCount = "SELECT COUNT($extendDisctionSQL) AS count FROM " . substr($sql,strpos($sqlBak," from ") + 6, strlen($sqlBak));
		}else{
			$sqlCount = "SELECT COUNT(0) AS count FROM " . substr($sql,strpos($sqlBak," from ") + 6, strlen($sqlBak));
		}
		//$sqlCount需要去除GROUP BY，不然统计不准确
		if(CommonUtil::contain($sqlCount,"GROUP BY")){
			$sqlCount = substr($sqlCount,0,strripos($sqlCount,"GROUP BY"));
		}
		$countArr = $model->query ( $sqlCount );
		$totalNum = 0;	//总记录数
		if(count($countArr) > 0){
			$totalNum = $countArr[0]["count"];
		}
		$totalPageNum = 0;	//总页数
		if ($totalNum % $numPerPage == 0) {
			$totalPageNum = (int)($totalNum / $numPerPage);
		} else {
			$totalPageNum = (int)($totalNum / $numPerPage) + 1;
		}
		$totalPageNum = $totalPageNum==0? 1: $totalPageNum;
		
		//第二步：组拼分页HTML代码
		$htmlurl = "<div class=\"pagination\">";
		//HTML URL 组拼[首页][下一页]
		if($currentPage > 1){
			if($currentPage == 2){
				if($isUrlDefault == 0){	//自定义URL模式替换模式
					if(CommonUtil::contain($url,"javascript:")){	//AJAX分页方式的替换方式
						$url4previous = str_replace(CommonType::$PAGE_NUM_TAG,1,$url);
					}else{	//自定义URL替换方式
						$replaceStr = "";
						if(CommonUtil::contain($url,"-".CommonType::$PAGE_NUM_TAG)){
							$replaceStr = "/";
						}else{
							$replaceStr = "";
						}
						if($isPureURL == TRUE){
							//去掉第“1”页参数
							$url4previous = str_replace("-".CommonType::$PAGE_NUM_TAG."/",$replaceStr,$url);
							$url4previous = str_replace("-".CommonType::$PAGE_NUM_TAG,"",$url4previous);
							$url4previous = str_replace(CommonType::$PAGE_NUM_TAG."/",$replaceStr,$url4previous);
							$url4previous = str_replace(CommonType::$PAGE_NUM_TAG,"",$url4previous);
						}else{
							$url4previous = str_replace(CommonType::$PAGE_NUM_TAG,1,$url);
						}
					}
				}else{	//缺省URL模块替换模式
					$url4previous = str_replace(CommonType::$PAGE_NUM_TAG,1,$url);
				}
				$htmlurl .= '<a href="'.$url4previous.'" target="_self">&nbsp;&lt;&nbsp;</a>';	//上一页
			}else{
				$htmlurl .= '<a href="'.str_replace(CommonType::$PAGE_NUM_TAG,$currentPage-1,$url).'" target="_self">&nbsp;&lt;&nbsp;</a>';	//上一页
			}
		}
	
		//HTML URL 组拼[1,2,3,4,5]
		$firstPageNumber = 0;	// 首页[5,6,7,8,9,10]末页   --->  则5为[$firstPageNumber]
		$endPageNumber = 0;		// 首页[5,6,7,8,9,10]末页   --->  则10为[$endPageNumber]
		$pageNumListSize = 10;	//分页数字显示的长度，如[1,2,3,4,5] 的长度则为5
		if ($currentPage % $pageNumListSize == 0) {
			$firstPageNumber = $currentPage;
		} else {
			$firstPageNumber = ((int) ($currentPage / $pageNumListSize)) * $pageNumListSize;
		}
		$appenerPageNum = 0;
		if (($totalPageNum - $firstPageNumber) < $pageNumListSize) {
			$appenerPageNum = $totalPageNum - $firstPageNumber;
		} else {
			$appenerPageNum = $pageNumListSize;
		}
		$endPageNumber = $firstPageNumber + $appenerPageNum;
		$firstPageNumber = $firstPageNumber==0? 1: $firstPageNumber;
		
		//首页标签显示
		if($currentPage > ($pageNumListSize -1)){
			if($isUrlDefault == 0){	//自定义URL模式替换模式
				if(CommonUtil::contain($url,"javascript:")){	//AJAX分页方式的替换方式
					$url4first = str_replace(CommonType::$PAGE_NUM_TAG,1,$url);
				}else{	//自定义URL替换方式
					$replaceStr = "";
					if(CommonUtil::contain($url,"-".CommonType::$PAGE_NUM_TAG)){
						$replaceStr = "/";
					}else{
						$replaceStr = "";
					}
					if($isPureURL == TRUE){
						//去掉第“1”页参数
						$url4first = str_replace("-".CommonType::$PAGE_NUM_TAG."/",$replaceStr,$url);
						$url4first = str_replace("-".CommonType::$PAGE_NUM_TAG,"",$url4first);
						$url4first = str_replace(CommonType::$PAGE_NUM_TAG."/",$replaceStr,$url4first);
						$url4first = str_replace(CommonType::$PAGE_NUM_TAG,"",$url4first);
					}else{
						$url4first = str_replace(CommonType::$PAGE_NUM_TAG,1,$url);
					}
					
				}
			}else{	//缺省URL模块替换模式
				$url4first = str_replace(CommonType::$PAGE_NUM_TAG,1,$url);
			}
			$htmlurl .= '<a href="'.$url4first.'" target="_self">1 ...</a>';	//首页标签
		}
		//分页数字标签显示
		for ($i = $firstPageNumber; $i <= $endPageNumber; $i++) {
			if($i == $currentPage){	//当前页
				$htmlurl .= '<span class="current">'.$i.'</span>';
			}else{
				if($i == 1){
					if($isUrlDefault == 0){	//自定义URL模式替换模式
						if(CommonUtil::contain($url,"javascript:")){	//AJAX分页方式的替换方式
							$url4fixed = str_replace(CommonType::$PAGE_NUM_TAG,1,$url);
						}else{	//自定义URL替换方式
							$replaceStr = "";
							if(CommonUtil::contain($url,"-".CommonType::$PAGE_NUM_TAG)){
								$replaceStr = "/";
							}else{
								$replaceStr = "";
							}
							if($isPureURL == TRUE){
								//去掉第“1”页参数
								$url4fixed = str_replace("-".CommonType::$PAGE_NUM_TAG."/",$replaceStr,$url);
								$url4fixed = str_replace("-".CommonType::$PAGE_NUM_TAG,"",$url4fixed);
								$url4fixed = str_replace(CommonType::$PAGE_NUM_TAG."/",$replaceStr,$url4fixed);
								$url4fixed = str_replace(CommonType::$PAGE_NUM_TAG,"",$url4fixed);
							}else{
								$url4fixed = str_replace(CommonType::$PAGE_NUM_TAG,1,$url);
							}
						}
					}else{	//缺省URL模块替换模式
						$url4fixed = str_replace(CommonType::$PAGE_NUM_TAG,1,$url);
					}
					$htmlurl .= '<a href="'.$url4fixed.'" target="_self">'.$i.'</a>';
				}else{
					$htmlurl .= '<a href="'.str_replace(CommonType::$PAGE_NUM_TAG,$i,$url).'" target="_self">'.$i.'</a>';
				}
			}
		}
		//末页标签显示
		if($currentPage < ($totalPageNum - $pageNumListSize +1)){
			$htmlurl .= '<a href="'.str_replace(CommonType::$PAGE_NUM_TAG,$totalPageNum,$url).'" target="_self">... '.$totalPageNum.'</a>';	//末页标签
		}
	
		//HTML URL 组拼[下一页][末页]
		if($currentPage < $totalPageNum){
			$htmlurl .= '<a href="'.str_replace(CommonType::$PAGE_NUM_TAG,$currentPage+1,$url).'" target="_self">下一页&nbsp;&gt;</a>';
		}
		$htmlurl.= '<div class="clear"></div></div>';
		if($totalPageNum == 1){
			$pagination["htmlurl"] = "";	//pagination的htmlurl赋值
		}else{
			$pagination["htmlurl"] = $htmlurl;	//pagination的htmlurl赋值
		}
		$pagination["totalNum"] = $totalNum;    //pagination的总共的条数
	
		//第三步：获取记录集 List
		$offset = ($currentPage - 1) * $numPerPage; //limit 的第一个参数计算
		$sql .= " LIMIT $offset,$numPerPage";
		$resultList = $model->query ( $sql );	//分页的记录集
		$pagination["resultList"] = $resultList;
		return $pagination;
	}
	
	
	
}